#include <stdio.h>
#include <stdlib.h>
#include <mqueue.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <string.h>
#include <unistd.h>
#include <signal.h>

#define QUEUE_NAME  "/mcu_command_queue"
#define MAX_MSG_SIZE 1024

int running = 1;

void sig_handler(int sig) {
    if (sig == SIGINT) {
        running = 0;
    }
}

int main() {
    signal(SIGINT, sig_handler);
    
    // 打开已存在的消息队列（只读）
    mqd_t mq = mq_open(QUEUE_NAME, O_RDONLY);
    if (mq == (mqd_t)-1) {
        perror("mq_open failed");
        return EXIT_FAILURE;
    }
    
    printf("Message queue reader started. Waiting for messages...\n");
    printf("Press Ctrl+C to exit.\n\n");
    
    char buffer[MAX_MSG_SIZE + 1];
    
    while (running) {
        memset(buffer, 0, sizeof(buffer));
        
        // 接收消息（阻塞模式）
        ssize_t bytes = mq_receive(mq, buffer, MAX_MSG_SIZE, NULL);
        if (bytes == -1) {
            perror("mq_receive failed");
            continue;
        }
        
        printf("Received message (%zd bytes): %s\n", bytes, buffer);
    }
    
    // 清理
    mq_close(mq);
    printf("\nReader exited cleanly.\n");
    
    return 0;
}